package org.budo.dubbo.protocol.async.util;

import org.budo.dubbo.protocol.async.BudoAsyncDubboProtocol;
import org.budo.dubbo.protocol.async.repository.BudoAsyncInvocation;
import org.budo.dubbo.serialize.util.DubboSerializeUtil;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.common.serialize.Serialization;
import com.alibaba.dubbo.rpc.Invoker;

/**
 * @author lmw
 */
public class AsyncSerializeUtil {
    public static BudoAsyncInvocation deserializeAsyncInvocation(byte[] messageBody, Invoker invoker) {
        URL url = null == invoker ? null : invoker.getUrl();
        Serialization serialization = AsyncSerializeUtil.getSerialization(url);

        return DubboSerializeUtil.deserialize(serialization, messageBody, BudoAsyncInvocation.class);
    }

    public static byte[] serializeAsyncInvocation(Object message, Invoker<?> invoker) {
        URL url = null == invoker ? null : invoker.getUrl();
        Serialization serialization = AsyncSerializeUtil.getSerialization(url);

        return DubboSerializeUtil.serializeResultValue(serialization, message, true);
    }

    /**
     * 默认 序列化方式为 java
     */
    protected static Serialization getSerialization(URL url) {
        String serialization = null == url //
                ? BudoAsyncDubboProtocol.DEFAULT_SERIALIZATION //
                : url.getParameter(Constants.SERIALIZATION_KEY, BudoAsyncDubboProtocol.DEFAULT_SERIALIZATION);

        ExtensionLoader<Serialization> extensionLoader = ExtensionLoader.getExtensionLoader(Serialization.class);
        return extensionLoader.getExtension(serialization);
    }
}